#include "tablemodel.h"
#include <QColor>
#include <QFont>
#include <QBrush>
#include <algorithm>

TableModel::TableModel(const QVector<ColumnConfig> &columns, QObject *parent)
    : QAbstractTableModel(parent), m_columns(columns)
{
}

int TableModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return m_data.size();
}

int TableModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return m_columns.size();
}

QVariant TableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_data.size() || index.column() >= m_columns.size())
        return QVariant();

    int row = index.row();
    if (!m_sortedIndices.isEmpty()) {
        row = m_sortedIndices.at(row);
    }

    const QMap<QString, QVariant> &rowData = m_data.at(row);
    const QString &fieldName = m_columns.at(index.column()).field;

    if (role == Qt::DisplayRole || role == Qt::EditRole) {
        return rowData.value(fieldName);
    } else if (role == Qt::TextAlignmentRole) {
        // 根据数据类型设置对齐方式
        QVariant value = rowData.value(fieldName);
        if (value.type() == QVariant::Int || value.type() == QVariant::Double) {
            return Qt::AlignRight + Qt::AlignVCenter;
        } else {
            return Qt::AlignLeft + Qt::AlignVCenter;
        }
    } else if (role == Qt::BackgroundRole) {
        // 交替行背景色
        if (index.row() % 2 == 0) {
            return QBrush(QColor(245, 245, 245));
        }
    }

    return QVariant();
}

QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal) {
        if (role == Qt::DisplayRole && section < m_columns.size()) {
            return m_columns.at(section).name;
        }
    } else if (orientation == Qt::Vertical) {
        if (role == Qt::DisplayRole) {
            return section + 1;
        }
    }

    return QVariant();
}

Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;

    // 如果列是可交互的，添加可点击标志
    if (isColumnInteractive(index.column())) {
        flags |= Qt::ItemIsEditable;
    }

    return flags;
}

void TableModel::setData(const QVector<QMap<QString, QVariant>> &data)
{
    beginResetModel();
    m_data = data;
    m_sortedIndices.clear();
    endResetModel();
}

void TableModel::sort(int column, Qt::SortOrder order)
{
    if (column < 0 || column >= m_columns.size() || !m_columns.at(column).sortable) {
        return;
    }

    beginResetModel();

    const QString &fieldName = m_columns.at(column).field;

    // 准备排序索引
    m_sortedIndices.resize(m_data.size());
    for (int i = 0; i < m_data.size(); ++i) {
        m_sortedIndices[i] = i;
    }

    // 排序
    std::sort(m_sortedIndices.begin(), m_sortedIndices.end(),
        [this, &fieldName, order](int left, int right) {
            const QVariant &leftValue = m_data.at(left).value(fieldName);
            const QVariant &rightValue = m_data.at(right).value(fieldName);

            if (order == Qt::AscendingOrder) {
                return leftValue < rightValue;
            } else {
                return leftValue > rightValue;
            }
        });

    endResetModel();
}

QVector<ColumnConfig> TableModel::getColumns() const
{
    return m_columns;
}

QString TableModel::getFieldName(int column) const
{
    if (column >= 0 && column < m_columns.size()) {
        return m_columns.at(column).field;
    }
    return QString();
}

bool TableModel::isColumnInteractive(int column) const
{
    if (column >= 0 && column < m_columns.size()) {
        return m_columns.at(column).interactive;
    }
    return false;
}
